package com.test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

public class Task implements Runnable {
    private String location;
    private AtomicInteger atomicInteger;
    private LinkedBlockingQueue<BufferedImage> imgQuque;

    public Task(String location, AtomicInteger atomicInteger, LinkedBlockingQueue<BufferedImage> imgQuque) {
        this.location = location;
        this.atomicInteger = atomicInteger;
        this.imgQuque = imgQuque;
    }

    //创建图片然后删掉
    public void run() {
        System.out.println(Thread.currentThread().getName() + " thread start");
        while (Start.flag) {
            atomicInteger.incrementAndGet();
//            生成
            String fileName = Util.getUuid() + ".jpg";
            try {
                BufferedImage bufferedImage = Util.getBufferedImage();
                boolean offer = imgQuque.offer(bufferedImage);
                if (offer) {
                    //如果进去了，那就进去吧，休眠一下继续
                    try {
                        Thread.sleep(3);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (!Start.flag) {
                        break;
                    }
                    continue;
                }
                ImageIO.write(bufferedImage, "jpg", new File(location + "/" + fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
//            删除
            File file = new File(location + "/" + fileName);
            boolean delete = file.delete();
            if (!delete) {
                throw new RuntimeException("delete fail");
            }
        }
        System.out.println(Thread.currentThread().getName() + " thread finish");
    }
}
